{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 1 将图像，带噪音图像，以及噪音图像通过Sobel算子、Scharr算子、Laplacian算子和Canny算子处理后的图像整合到一张图上比较。",
   "id": "f172d3d9d18973db"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-30T03:12:14.837163Z",
     "start_time": "2025-10-30T03:12:13.243034Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "\n",
    "# 新增：等比例缩小函数（仅新增此函数）\n",
    "def resize_img(img, scale=0.6):  # scale控制缩放比例，0.6表示缩小到60%（可调整）\n",
    "    h, w = img.shape[:2]\n",
    "    return cv.resize(img, (int(w*scale), int(h*scale)), interpolation=cv.INTER_AREA)\n",
    "\n",
    "def add_colored_noise(img, intensity=50):\n",
    "    row, col, ch = img.shape\n",
    "    colored_noise = np.random.randint(-intensity, intensity, img.shape)\n",
    "    noise_image = np.clip(img + colored_noise, 0, 255)\n",
    "    return noise_image.astype(np.uint8)\n",
    "\n",
    "original_image = cv.imread('./mm.png')\n",
    "\n",
    "noise_image = add_colored_noise(original_image)\n",
    "sobel_x = cv.Sobel(original_image, cv.CV_64F, 1, 0, ksize=3)\n",
    "sobel_y = cv.Sobel(original_image, cv.CV_64F, 0, 1, ksize=3)\n",
    "scharr_x = cv.Scharr(original_image, cv.CV_64F, 1, 0)\n",
    "scharr_y = cv.Scharr(original_image, cv.CV_64F, 0, 1)\n",
    "laplacian = cv.Laplacian(original_image, cv.CV_64F)\n",
    "canny = cv.Canny(original_image, 50, 150)\n",
    "edges_bgr = cv.merge([canny, canny, canny])\n",
    "shared_params = {\n",
    "    \"org\": (10, 30),\n",
    "    \"fontFace\": cv.FONT_HERSHEY_SIMPLEX,\n",
    "    \"fontScale\": 1,\n",
    "    \"thickness\": 2,\n",
    "    \"color\": (0, 255, 0),\n",
    "    \"lineType\": cv.LINE_AA,\n",
    "}\n",
    "\n",
    "original_image = cv.putText(original_image.copy(), \"Original\", **shared_params)\n",
    "original_image = resize_img(original_image)\n",
    "\n",
    "noise_image = cv.putText(noise_image.copy(), \"Noise\",** shared_params)\n",
    "noise_image = resize_img(noise_image)\n",
    "\n",
    "sobel_xy_image = cv.putText(cv.convertScaleAbs(sobel_x + sobel_y), \"Sobel\", **shared_params)\n",
    "sobel_xy_image = resize_img(sobel_xy_image)\n",
    "\n",
    "scharr_xy_image = cv.putText(cv.convertScaleAbs(scharr_x+scharr_y), \"Scharr\",** shared_params)\n",
    "scharr_xy_image = resize_img(scharr_xy_image)\n",
    "\n",
    "laplacian_image = cv.putText(cv.convertScaleAbs(laplacian), \"Laplacian\", **shared_params)\n",
    "laplacian_image = resize_img(laplacian_image)\n",
    "\n",
    "edges_mid_image = cv.putText(edges_bgr, \"Canny\",** shared_params)\n",
    "edges_mid_image = resize_img(edges_mid_image)\n",
    "\n",
    "row1 = cv.hconcat([original_image, noise_image, sobel_xy_image])\n",
    "row2 = cv.hconcat([scharr_xy_image, laplacian_image, edges_mid_image])\n",
    "scharr_image = cv.vconcat([row1, row2])\n",
    "\n",
    "cv.imshow(\"Noise\", scharr_image)\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ],
   "id": "91cca2b136979a88",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 2.将图像及经过腐蚀，膨胀，开运算、闭运算，礼帽运算，黑帽运算，粗化、细化运算后的图像整合到一张图上做比较。",
   "id": "2ed99020479d38c1"
  },
  {
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "cell_type": "code",
   "source": [
    "import cv2 as cv\n",
    "import numpy as np\n",
    "\n",
    "image = cv.imread(\"./ecllipse.png\")\n",
    "rect_kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n",
    "dialated_image = cv.dilate(image, rect_kernel, iterations=1)\n",
    "eroded_image = cv.erode(image, rect_kernel, iterations=1)\n",
    "\n",
    "def draw_connected_image(src_img):\n",
    "    gray_img = cv.cvtColor(src_img, cv.COLOR_BGR2GRAY)\n",
    "    threshold_value = 20\n",
    "    _, binary_img = cv.threshold(gray_img, threshold_value, 255, cv.THRESH_BINARY)\n",
    "    _, labels, stats, centroids = cv.connectedComponentsWithStats(binary_img)\n",
    "    num_labels = len(stats) - 1\n",
    "    for i in range(1, num_labels + 1):\n",
    "        x,y,w,h,_ = stats[i]\n",
    "        cv.rectangle(src_img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n",
    "    return src_img\n",
    "\n",
    "white = {\n",
    "    \"org\": (10,30),\n",
    "    \"fontFace\": cv.FONT_HERSHEY_SIMPLEX,\n",
    "    \"fontScale\": 1,\n",
    "    \"thickness\": 2,\n",
    "    \"color\": (255,255,255),\n",
    "    \"lineType\": cv.LINE_AA\n",
    "}\n",
    "\n",
    "black = white.copy()\n",
    "black[\"color\"] = 0\n",
    "black[\"thickness\"] = 10\n",
    "\n",
    "img_txt = cv.putText(image.copy(), \"Original Image\", **black)\n",
    "img_txt = cv.putText(img_txt, \"Original Image\", **white)\n",
    "detailed_img_txt = cv.putText(dialated_image.copy(), \"Dialated Image\", **black)\n",
    "detailed_img_txt = cv.putText(detailed_img_txt.copy(), \"Dialated Image\", **white)\n",
    "eroded_image_txt = cv.putText(eroded_image.copy(), f\"Eroded Image\", **black)\n",
    "eroded_image_txt = cv.putText(eroded_image_txt, f\"Eroded Image\", **white)\n",
    "\n",
    "module1 = cv.hconcat([img_txt, draw_connected_image(image.copy())])\n",
    "module2 = cv.hconcat([detailed_img_txt, draw_connected_image(dialated_image.copy())])\n",
    "module3 = cv.hconcat([eroded_image_txt, draw_connected_image(eroded_image.copy())])\n",
    "\n",
    "separator = np.zeros((10, module1.shape[1], 3), dtype=np.uint8) + 255\n",
    "final_img = cv.vconcat([module1, separator, module2, separator, module3])\n",
    "\n",
    "cv.imshow('Comparison', final_img)\n",
    "\n",
    "cv.waitKey(0)\n",
    "cv.destroyAllWindows()"
   ],
   "id": "9f024a58c828529c",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
